package net.oschina.app.fragment;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.encoding.EncodingHandler;

import net.oschina.app.R;
import net.oschina.app.bean.LoginBean;
import net.oschina.app.interf.Constants;
import net.oschina.app.interf.FragmentType;
import net.oschina.app.service.ApiService;
import net.oschina.app.ui.RvFragmentActivity;
import net.oschina.app.util.CommonUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by wei03 on 2017/1/12.
 */
public class MeFragment extends Fragment {
    @BindView(R.id.iv_gender)
    ImageView mIvGender;
    @BindView(R.id.iv_mafe)
    ImageView mIvMafe;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.iv_qr_code1)
    ImageView mIvQrCode1;
    @BindView(R.id.tv_score)
    TextView mTvScore;
    @BindView(R.id.ly_score)
    LinearLayout mLyScore;
    @BindView(R.id.tv_favorite)
    TextView mTvFavorite;
    @BindView(R.id.ly_favorite)
    LinearLayout mLyFavorite;
    @BindView(R.id.tv_following)
    TextView mTvFollowing;
    @BindView(R.id.ly_following)
    LinearLayout mLyFollowing;
    @BindView(R.id.tv_follower)
    TextView mTvFollower;
    @BindView(R.id.ly_follower)
    LinearLayout mLyFollower;
    @BindView(R.id.tv_mes)
    TextView mTvMes;
    @BindView(R.id.rl_message)
    LinearLayout mRlMessage;
    @BindView(R.id.rl_blog)
    LinearLayout mRlBlog;
    @BindView(R.id.rl_note)
    LinearLayout mRlNote;
    @BindView(R.id.rl_team)
    LinearLayout mRlTeam;
    @BindView(R.id.rootview)
    LinearLayout mRootview;
    @BindView(R.id.customerScrollView)
    ScrollView mCustomerScrollView;
    private EditText mMUser;
    private EditText mMPassword;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_my_information, container, false);
        ButterKnife.bind(this, view);
        mTvScore.setText("0");
        mTvFavorite.setText("11");
        mTvFollowing.setText("6");
        mTvFollower.setText("2");
        return view;
    }

    @OnClick({R.id.iv_gender, R.id.ly_favorite, R.id.ly_following, R.id.ly_follower, R.id.rl_message, R.id.rl_blog, R.id.rl_note, R.id.rl_team, R.id.iv_qr_code1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ly_favorite:
                showMeDetailActivity(FragmentType.TYPE_ME_FAVORITE);
//                startActivity(new Intent(getContext(), MeFavoriteActivity.class));
                break;
            case R.id.ly_following:
                showMeDetailActivity(FragmentType.TYPE_ME_FANS);
//                startActivity(new Intent(getContext(), MeFollowActivity.class));
                break;
            case R.id.ly_follower:
                showMeDetailActivity(FragmentType.TYPE_ME_FANS);
//                startActivity(new Intent(getContext(), MeFollowActivity.class));
                break;
            case R.id.rl_message:
                showMeDetailActivity(FragmentType.TYPE_ME_MESSAGE);
//                startActivity(new Intent(getContext(), MeMessageActivity.class));
                break;
            case R.id.rl_blog:
                showMeDetailActivity(FragmentType.TYPE_ME_BLOG);
                break;
            case R.id.rl_note:
                break;
            case R.id.iv_gender:  //头像
                login();
                break;
            case R.id.rl_team:
                break;
            case R.id.iv_qr_code1:
                openQRCodeDialog();
                break;
        }
    }

    private void openQRCodeDialog() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.head);
        Bitmap www = EncodingHandler.createQRCode("http://www.sina.com.cn/", CommonUtils.dp2px(300), CommonUtils.dp2px(200), bitmap);

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
//        AlertDialog customDialog;
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.qrcode, null);

        ImageView ivqrCode = (ImageView) layout.findViewById(R.id.iv_qrcode);
        ivqrCode.setImageBitmap(www);
        builder.setView(layout);
        builder.show();
    }

    private void showMeDetailActivity(String type) {
        Intent intent = new Intent(getContext(), RvFragmentActivity.class);
        intent.putExtra(FragmentType.FRAGMENT_TYPE, type);
        startActivity(intent);
    }

    private void login() {
        loginDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
//                LoginBean loginBean = new BaseProtocol<LoginBean>() {
//                    @Override
//                    protected Call<LoginBean> getCall(String pageIndex) {
//                        //_user_behavior_=6e32603d-82df-4859-86ad-ec9aa3a7f1b9; oscid=JdSug%2BX5P3gq4C%2F6SbsYtV2OGtyiCn5wpbFicjzco1DoMXEZq5sUhv7ZSZ1Bp3G9yHaANKE0OB77ipnEZQAq3oaXkyJ5NJ82qL4FmHJ%2BX%2F4K6Ey8AcaShvhSyArLkcAYIT2Tq5qEPFYahAwSwXtBXw%3D%3D
//                        return mApiService.getLoginBean("15259799703", "wonderful2016", "1");
//                    }
//                }.getData(0);
//                final String errorMessage = loginBean.getResult().getErrorMessage();
//                CommonUtils.runOnMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show();
//                    }
//                });
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Constants.HOST)
                        .addConverterFactory(SimpleXmlConverterFactory.create())
                        .build();
                ApiService mApiService = retrofit.create(ApiService.class);
                Call<LoginBean> loginBeanCall = mApiService.getLoginBean("13265316412", "suju5201314", "1");
                loginBeanCall.enqueue(new Callback<LoginBean>() {
                    @Override
                    public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                        Headers headers = response.headers();
                        String s = headers.get("Set-Cookie");
                        System.out.println(s + "+++++++++");
                        LoginBean body = response.body();
                        String message = body.getResult().getErrorMessage();
                        //Toast.makeText(CommonUtils.getContext(), message, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(Call<LoginBean> call, Throwable t) {
                        t.printStackTrace();
                    }

                });

            }
        }).start();

    }

    private void loginDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_user_login, null);
        View layout1 = inflater.inflate(R.layout.aa, null);
        mMUser = (EditText) layout.findViewById(R.id.user);
        mMPassword = (EditText) layout.findViewById(R.id.password);
        builder.setIcon(android.R.drawable.title_bar);
        builder.setCustomTitle(layout1);
        builder.setCancelable(false);
        builder.setView(layout);
        builder.setPositiveButton("登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String user = mMUser.getText().toString();
                String password = mMPassword.getText().toString();
                if (user.equals("a") && password.equals("123")) {
                    mProgress = ProgressDialog.show(getActivity(), "", "正在登录");
                    // 新线程，睡眠3秒然后关闭ProgressDialog
                    new Thread() {
                        public void run() {
                            SystemClock.sleep(3000);
                            mProgress.dismiss();
                            CommonUtils.runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }.start();
                    dialog.dismiss();
                } else {
                    Toast.makeText(getActivity(), "用户名或者密码不正确,请重新输入", Toast.LENGTH_SHORT).show();
                }
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                CommonUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        builder.show();
    }

    private ProgressDialog mProgress;

}
